<template>
  <div class="comprehensive-table-container">
    <div
      style="
        color: #fa6567;
        font-weight: bold;
        font-size: 18px;
        margin-bottom: 20px;
        margin-left: 10px;
      "
    >
      管理后台登录人员，最高权限管理员不可以直接删除，可以降权再删除。当最高管理员仅剩一人，无法降权和删除。无法降权和删除您正在登录的账号
    </div>
    <vab-query-form>
      <vab-query-form-top-panel>
        <el-form
          :inline="true"
          label-width="80px"
          :model="queryForm"
          @submit.prevent
        >
          <el-form-item label="综合检索">
            <el-input
              v-model="queryForm.title"
              placeholder="姓名、联系电话或登录账号"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              icon="el-icon-search"
              native-type="submit"
              style="
                background-color: #58b5e1;
                color: #fff;
                border: 0px;
                font-size: 14px;
              "
              @click="queryData"
            >
              查询
            </el-button>
          </el-form-item>
          <template v-for="(item, index) in service_tel" :key="index">
            <el-form-item label="">
              <el-input
                v-show="showEditService"
                v-model="service_tel[index]"
                placeholder="请输入客服电话"
                style="width: 120px"
              />
            </el-form-item>
            <el-form-item label="">
              <el-button
                v-show="showEditService"
                icon="el-icon-delete"
                style="
                  margin: 0 0 0 2px !important;
                  padding: 9px 5px !important;
                  background-color: #fa6567;
                  color: #fff;
                  border: 0px;
                "
                @click="service_tel.splice(index, 1)"
              />
            </el-form-item>
            &ensp;
          </template>
          <el-form-item label="">
            <el-button
              v-show="showEditService"
              icon="el-icon-plus"
              style="margin: 0 0 0 0 !important; padding: 9px 5px !important"
              @click="close"
            >
              取 消
            </el-button>
          </el-form-item>
          <el-form-item label="">
            <el-button
              v-show="showEditService"
              icon="el-icon-refresh-left"
              style="
                background-color: #58b5e1;
                color: #fff;
                border: 0px;
                font-size: 14px;
                margin: 0 0 0 10px !important;
                padding: 9px 5px !important;
              "
              @click="getServiceInfo()"
            />
          </el-form-item>

          <el-form-item label="">
            <el-button
              v-show="showEditService"
              style="
                background-color: #58b5e1;
                color: #fff;
                border: 0px;
                font-size: 14px;
              "
              @click="handleEditService()"
            >
              确认
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-top-panel>
      <vab-query-form-left-panel :span="24">
        <el-button
          icon="el-icon-plus"
          style="
            background-color: #58b5e1;
            color: #fff;
            border: 0px;
            font-size: 14px;
          "
          @click="handleAdd"
        >
          添加
        </el-button>
        <el-button
          icon="el-icon-delete"
          style="
            background-color: #fa6567;
            color: #fff;
            border: 0px;
            font-size: 14px;
          "
          @click="handleDelete($event)"
        >
          删除
        </el-button>
      </vab-query-form-left-panel>
    </vab-query-form>

    <el-table
      ref="tableSortRef"
      v-loading="listLoading"
      border
      :cell-style="{ padding: '4px 0 4px 0' }"
      :data="list"
      :header-cell-style="{
        background: '#E1EAF3 !important',
        'text-align': 'center',
      }"
      :height="500"
      :row-style="{ background: '#E4F2FF' }"
      stripe
      @selection-change="setSelectRows"
      @sort-change="tableSortChange"
    >
      <el-table-column
        align="center"
        show-overflow-tooltip
        type="selection"
        width="55"
      />
      <el-table-column
        align="center"
        label="序号"
        show-overflow-tooltip
        width="55"
      >
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="登录账号"
        prop="username"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="真实姓名"
        prop="realName"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="角色"
        prop="role"
        show-overflow-tooltip
      />
      <!-- <el-table-column align="center" label="头像" width="80">
          <template #default="{ row }">
            <el-image
              v-if="imgShow"
              :preview-src-list="imageList"
              :src="row.avatarUrl"
            />
          </template>
        </el-table-column> -->
      <el-table-column
        align="center"
        label="最近ip"
        prop="lastIp"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="登录数"
        prop="loginNum"
        show-overflow-tooltip
        width="90"
      />
      <el-table-column
        align="center"
        label="状态"
        prop="status"
        show-overflow-tooltip
        width="140"
      >
        <template #default="{ row }">
          <el-tooltip
            class="item"
            :content="row.status === 1 ? '禁用' : '启用'"
            effect="dark"
            :enterable="false"
            placement="top"
          >
            <span>
              <el-switch
                v-if="row.roleCode !== 'SUPER_ADMIN'"
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                @change="changeUserSatus(row)"
              />
            </span>
          </el-tooltip>
          <el-tag :type="statusFilter(row.status)">
            {{ row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="上次登录"
        prop="lastTime"
        show-overflow-tooltip
        width="160"
      />
      <el-table-column
        align="center"
        fixed="right"
        label="操作"
        show-overflow-tooltip
        width="130"
      >
        <template #default="{ row }">
          <el-button type="text" @click="handleDetail(row)">详情</el-button>
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button
            v-if="row.roleCode !== 'SUPER_ADMIN'"
            type="text"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <table-edit ref="editRef" @fetch-data="fetchData" />
    <!-- </el-col> -->
    <!-- </el-row> -->
  </div>
</template>

<script>
  import {
    computed,
    defineComponent,
    getCurrentInstance,
    onBeforeMount,
    onBeforeUnmount,
    onMounted,
    reactive,
    toRefs,
    watch,
  } from 'vue'
  import { useStore } from 'vuex'
  import { useRouter, useRoute } from 'vue-router'
  import { changeStatus, doDelete, getList } from '@/api/system_admin'
  // import { getTree } from '@/api/department'
  import { handleMatched, handleTabs } from '@/utils/routes'
  import TableEdit from './components/TableEdit'

  export default defineComponent({
    name: 'ComprehensiveTable',
    components: {
      TableEdit,
    },
    setup() {
      const store = useStore()
      const router = useRouter()
      const route = useRoute()
      const routes = computed(() => store.getters['routes/routes'])
      const changeTabsMeta = (options) =>
        store.dispatch('tabs/changeTabsMeta', options)
      const addVisitedRoute = (options) =>
        store.dispatch('tabs/addVisitedRoute', options)
      const { proxy } = getCurrentInstance()

      const state = reactive({
        editRef: null,
        tableSortRef: null,
        fold: false,
        height: proxy.$baseTableHeight(2) - 30,
        imgShow: true,
        list: [],
        imageList: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        showEditService: false,
        service_tel: [],
        queryForm: {
          pageNo: 1,
          pageSize: 30,
        },
        defaultProps: {
          children: 'children',
          label: 'name',
        },
        data: [],
        openIds: [],
        filterText: '',
      })

      watch(
        () => route.path,
        (value) => {
          if (value === '/system/admin/comprehensiveTable') fetchData()
        }
      )

      const fetchData = async () => {
        state.listLoading = true
        const {
          data: { records: list, total },
        } = await getList(state.queryForm)
        state.list = list
        const imageList = []
        list.forEach((item) => {
          console.log(item.avatarUrl)
          imageList.push(item.avatarUrl)
        })
        state.imageList = imageList
        state.total = total
        state.listLoading = false
      }
      // const getDepartmentTree = async () => {
      //   const {
      //     data: { tree, ids },
      //   } = await getTree()
      //   state.data = tree
      //   state.openIds = ids
      // }
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.pageNo = 1
        fetchData()
      }
      const statusFilter = (status) => {
        const statusMap = {
          published: 'success',
          draft: 'gray',
          deleted: 'danger',
        }
        return statusMap[status === 1 ? 'published' : 'deleted']
      }
      const filterTree = () => {
        if (!state.filterText) return
      }
      const handleFold = () => {
        state.fold = !state.fold
        handleHeight()
      }
      const handleHeight = () => {
        if (state.fold) state.height = proxy.$baseTableHeight(2) - 47
        else state.height = proxy.$baseTableHeight(3) - 30
      }
      const tableSortChange = () => {
        const imageList = []
        state['tableSortRef'].tableData.forEach((item) => {
          imageList.push(item.img)
        })
        this.imageList = imageList
      }
      const setSelectRows = (val) => {
        state.selectRows = val
      }
      const handleAdd = () => {
        state['editRef'].showEdit()
      }
      const handleEdit = (row) => {
        state['editRef'].showEdit(row)
      }
      const handleDelete = (row) => {
        let arr = []
        if (row.id) {
          proxy.$baseConfirm('你确定要删除当前项吗', null, async () => {
            arr.push(row.id)
            const { msg } = await doDelete({ ids: arr })
            proxy.$baseMessage(msg, 'success', 'vab-hey-message-success')
            await fetchData()
          })
        } else {
          if (state.selectRows.length > 0) {
            state.selectRows.map((item) => arr.push(item.id))
            proxy.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids: arr })
              proxy.$baseMessage(msg, 'success', 'vab-hey-message-success')
              await fetchData()
            })
          } else {
            proxy.$baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }

      const changeUserSatus = async (row) => {
        let obj = {
          id: row.id,
          status: row.status,
        }
        const { msg } = await changeStatus(obj)
        proxy.$baseMessage(msg, 'success', 'vab-hey-message-success')
      }
      const handleDetailStayTable = async () => {
        for (let i = 0; i < state.selectRows.length; i++) {
          const matched = handleMatched(routes.value, 'Detail')
          const tab = handleTabs(
            {
              ...matched[matched.length - 1],
              query: state.selectRows[i],
            },
            true
          )
          if (tab) {
            await addVisitedRoute(tab)
            changeTabsMeta({
              title: '详情页',
              meta: {
                title: `${tab.query.title} 详情页`,
              },
            })
          }
        }
      }

      const handleDetail = (row) => {
        if (row.id)
          router.push({
            path: '/admin/adminUser/detail',
            query: row,
          })
        else {
          proxy.$baseMessage(
            '请选择一行进行详情页跳转',
            'error',
            'vab-hey-message-error'
          )
        }
      }
      const handleMessage = () => {
        proxy.$baseMessage('test1', 'success', false, 'vab-hey-message-success')
      }
      const handleAlert = () => {
        proxy.$baseAlert('11')
        // proxy.$baseAlert('11', '自定义标题', () => {
        //   /* 可以写回调; */
        // })
        // proxy.$baseAlert('11', null, () => {
        //   /* 可以写回调; */
        // })
      }
      const handleConfirm = () => {
        proxy.$baseConfirm(
          '你确定要执行该操作?',
          null,
          () => {
            /* 可以写回调; */
          },
          () => {
            /* 可以写回调; */
          }
        )
      }
      const handleNotify = () => {
        proxy.$baseNotify('测试消息提示', 'test', 'success', 'bottom-right')
      }

      const handleNodeClick = (data) => {
        console.log(data)
      }

      onBeforeMount(() => {
        window.addEventListener('resize', handleHeight)
      })
      onBeforeUnmount(() => {
        window.removeEventListener('resize', handleHeight)
      })
      onMounted(() => {
        fetchData()
        // getDepartmentTree()
      })

      return {
        ...toRefs(state),
        handleSizeChange,
        handleCurrentChange,
        queryData,
        statusFilter,
        handleFold,
        handleHeight,
        tableSortChange,
        setSelectRows,
        handleAdd,
        changeUserSatus,
        handleEdit,
        handleDelete,
        handleDetailStayTable,
        handleDetail,
        handleMessage,
        handleAlert,
        handleConfirm,
        handleNotify,
        fetchData,
        handleNodeClick,
        filterTree,
      }
    },
    methods: {},
  })
</script>
